<template>
    <section>
        <div style="margin-bottom:5px;">
            <el-input placeholder="请输入内容" size="small" v-model="searchKey" style="width: 250px;">
                <el-button slot="append" size="small" icon="el-icon-search" @click="getDataList"></el-button>
            </el-input>
            <el-button type="primary" size="small" @click="openAddDialog()">新 建</el-button>
        </div>
        <el-table ref="multipleTable" :data="dataList" border tooltip-effect="dark" style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" label="序号">
            </el-table-column>

            <el-table-column prop="name" label="名称">
            </el-table-column>
            <el-table-column prop="accessUrl" label="访问URL">
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status===1" type="success">上架</el-tag>
                    <el-tag v-else type="danger">下架</el-tag>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button size="mini" type="primary" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="removeItem(scope.row)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <div style="text-align: right;background: rgb(239, 242, 247);border: 1px solid #E5E9F2;">
            <el-pagination style="line-height: 30px; height: 30px;" @size-change="handleSizeChange"
                           @current-change="handleCurrentChange" :current-page="currentPage"
                           :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <div v-if="dialogFormVisibleAdd">
            <el-dialog :title="dialogAddOrEdit" :visible="dialogFormVisibleAdd" :modal="dialogFormVisibleAdd"
                       :before-close="openAddDialogClose">

                <el-form label-width="100px" :rules="formAddRules" :model="formAdd" ref="formAdd">

                    <el-row>

                        <el-col :span=12>
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="formAdd.name" style="width: 100%"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span=12>
                            <el-form-item>
                                <el-switch :active-value='1' :inactive-value="0" activeText="上架" inactiveText="下架"
                                           v-model="formAdd.status"></el-switch>
                            </el-form-item>

                        </el-col>

                    </el-row>

                    <el-row>
                        <el-col :span=24>
                            <el-form-item label="访问URL" prop="accessUrl">
                                <el-input v-model="formAdd.accessUrl" style="width: 100%"></el-input>
                            </el-form-item>
                        </el-col>


                    </el-row>

                    <el-row>
                        <el-col :span=24>
                            <el-form-item label="网关处理" prop="operation">
                                <el-radio-group v-model="formAdd.operation">
                                    <el-radio :label="0">转向</el-radio>
                                    <el-radio :label="1">自定义报错</el-radio>
                                    <el-radio :label="2">统一网关异常</el-radio>
                                    <el-radio :label="3">限流</el-radio>
                                </el-radio-group>
                            </el-form-item>

                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span=24>
                            <el-form-item label="转向地址" prop="redirectUrl" v-if="formAdd.operation ==0">
                                <el-input v-model="formAdd.redirectUrl" style="width: 100%"></el-input>
                            </el-form-item>
                            <el-form-item label="出错信息" prop="errorMsg" v-if="formAdd.operation ==1">
                                <el-input type="textarea" v-model="formAdd.errorMsg" style="width: 100%"></el-input>
                            </el-form-item>
                            <el-form-item label="最大请求数" prop="burstCapacity" v-if="formAdd.operation ==3">
                                <el-input v-model="formAdd.burstCapacity" style="width: 100%"></el-input>
                                <div>* 令牌桶的容量，允许在一秒钟内完成的最大请求数</div>
                            </el-form-item>

                            <el-form-item label="请求平均数" prop="replenishRate" v-if="formAdd.operation ==3">
                                <el-input v-model="formAdd.replenishRate" style="width: 100%"></el-input>
                                <div>* 令牌桶每秒填充平均速率,即行等价于允许用户每秒处理多少个请求平均数</div>
                            </el-form-item>


                        </el-col>

                    </el-row>

                    　
                    <el-form-item>
                        <el-button type="primary" @click="submitFormAdd('formAdd')">保存</el-button>
                        <el-button type="primary" @click="openTestUrlDialog">测试</el-button>

                        <el-button @click="openAddDialogClose">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>

        <div v-if="testUrl.dialogFormVisible">
            <el-dialog title="测试请求" :visible="testUrl.dialogFormVisible" :modal="testUrl"
                       :before-close="openTestUrlDialogClose">

                <el-form label-width="100px">


                    <el-row>
                        <el-col :span=24>
                            <el-form-item label="访问URL">
                                <el-input v-model="formAdd.accessUrl" style="width: 100%" readonly="true"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item>
                        <el-button type="primary" @click="testAccess()">请求</el-button>
                        <el-button @click="openTestUrlDialogClose">取消</el-button>
                    </el-form-item>
                    <el-row>
                        <el-col :span=24>
                            <el-form-item label="返回信息" prop="responseMessage">
                                <el-input type="textarea" v-model="testUrl.responseMessage"
                                          style="width: 100%"></el-input>
                            </el-form-item>
                        </el-col>

                    </el-row>


                </el-form>
            </el-dialog>
        </div>
    </section>
</template>
<style>

</style>
<script>
    import {AjaxByAll} from '@/api/api';

    export default {

        data() {

            return {
                dataList: [],
                multipleSelection: [],
                dialogFormVisibleAdd: false,
                labelPosition: 'left',
                formAdd: {
                    id: null,
                    name: null,
                    accessUrl: null,
                    status: null,
                    operation: null,
                    redirectUrl: null,
                    errorMsg: null,

                    /**
                     * 令牌桶的容量，允许在一秒钟内完成的最大请求数
                     */
                    burstCapacity: null,


                    /**
                     * 令牌桶每秒填充平均速率,即行等价于允许用户每秒处理多少个请求平均数
                     */
                    replenishRate: null,


                },
                testUrl: {
                    dialogFormVisible: false,
                    responseMessage: null,
                },
                pageSize: 10,
                currentPage: 1,
                total: 0,
                dialogAddOrEdit: '',
                searchKey: null, defaultData: null,
                formAddRules: {
                    name: [
                        {
                            required: true,
                            message: "请输入名称",
                            trigger: "change"
                        },
                    ]
                    ,
                    accessUrl: [
                        {
                            required: true,
                            message: "请输入访问URL",
                            trigger: "change"
                        },
                    ]
                    ,
                    burstCapacity: [

                        {
                            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                            message: "请输入合法的数字，最多两位小数",
                            trigger: "change"
                        }
                    ]
                    ,
                    replenishRate: [

                        {
                            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                            message: "请输入合法的数字，最多两位小数",
                            trigger: "change"
                        }
                    ]

                }
            }
        },

        methods: {

            openDialog(model) {

                if (model) {
                    let id = model.id;
                    this.dialogAddOrEdit = '编辑 工程特定网址管理';
                    let urls = 'gateway/project/spec/url/' + id;
                    let method = 'get';
                    let form = {};
                    AjaxByAll(method, urls, form).then(data => {
                        if (data.code === 200) {
                            this.formAdd = data.data;
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                }
                this.dialogFormVisibleAdd = true;
            },
            openAddDialog() {
                this.dialogAddOrEdit = '新建工程特定网址管理';
                // 送出後
                this.$data.formAdd = Object.assign(this.$data.formAdd, this.defaultData);
                this.dialogFormVisibleAdd = true;
            },
            openAddDialogClose() {

                this.dialogFormVisibleAdd = false;
            },
            openTestUrlDialog() {

                this.testUrl.dialogFormVisible = true;
            },
            openTestUrlDialogClose() {

                this.testUrl.dialogFormVisible = false;
            },
            testAccess() {
                let form = {};
                AjaxByAll('get', this.formAdd.accessUrl, form).then(data => {

                    this.testUrl.responseMessage = JSON.stringify(data);
                });
            },
            getDataList() {
                let self = this;
                let form = {
                    currentPage: self.currentPage,
                    pageSize: self.pageSize,
                    keyword: self.searchKey
                };
                let urls = 'gateway/project/spec/url/query';
                AjaxByAll('post', urls, form).then(data => {
                    if (data.code === 200) {

                        self.total = data.data.total * 1;
                        self.dataList = data.data.records;
                    }

                    this.loading = false;
                });
            },
            submitFormAdd(formName) {

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let form = this.formAdd;
                        let urls = 'gateway/project/spec/url/';
                        let method = this.formAdd.id
                        == null ? 'post' : 'put';
                        AjaxByAll(method, urls, form).then(data => {
                            if (data.code === 200) {
                                this.formAdd.id = data.data;
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });

                                this.getDataList();
                            } else {
                                this.$message({
                                    message: data.msg,
                                    type: 'error'
                                });
                            }
                            this.dialogFormVisibleAdd = !this.dialogFormVisibleAdd;
                        });


                    } else {
                        this.$message({
                            message: '校验失败',
                            type: 'error'
                        });
                    }
                });
            },
            removeItem(model) {
                this.$confirm('确认移除吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    AjaxByAll('delete', 'gateway/project/spec/url/' + model.id, null).then(data => {
                        if (data.code === 200) {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.getDataList();
                        } else {
                            this.$message({
                                message: '操作失败：' + data.msg,
                                type: 'error'
                            });
                        }

                    });
                }).catch(() => {

                });
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                //  console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.getDataList();
            },
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.getDataList();
            }
        },
        created() {

        }, computed: {},
        mounted: function () {
            this.getDataList();
            this.defaultData = JSON.parse(JSON.stringify(this.formAdd));
        }
    }
</script>